'use strict';

// 设备物理参数
const ANGLE_STEPS_PER_RADIAN = 1308.997; // 8200步/360° → 1308.997步/弧度
const RADIUS_STEPS_TOTAL = 4400; // 半径轴最大步数
const DEFAULT_SPEED = 400; // 默认绘图速度(步/秒)
const COMPENSATION_FACTOR = 0.25; // 补偿系数

exports.main = async (event, context) => {
  const { fileContent } = event;
  
  if (!fileContent) {
    return { 
      code: -1, 
      message: '缺少fileContent参数' 
    };
  }
  
  try {
    console.log('开始计算时长');
    
    // 1. 解析文件内容
    const lines = fileContent.split('\n').filter(line => {
      line = line.trim();
      // 过滤空行和注释行
      if (!line || line.startsWith('#')) return false;
      // 确保行包含两个数值
      const parts = line.split(/\s+/);
      return parts.length >= 2 && !isNaN(parseFloat(parts[0])) && !isNaN(parseFloat(parts[1]));
    });
    
    console.log('解析到有效数据行数:', lines.length);
    
    // 2. 解析坐标点
    const points = lines.map(line => {
      const [theta, rho] = line.trim().split(/\s+/).map(Number);
      return { theta, rho };
    });
    
    if (points.length < 2) {
      return { 
        code: -1, 
        message: 'THR文件格式错误或点数不足(至少需要2个点)' 
      };
    }
    
    // 3. 计算总时长
    let totalTime = 0;
    
    for (let i = 1; i < points.length; i++) {
      const p1 = points[i - 1];
      const p2 = points[i];
      
      // 转换为步数
      const theta1Steps = p1.theta * ANGLE_STEPS_PER_RADIAN;
      const theta2Steps = p2.theta * ANGLE_STEPS_PER_RADIAN;
      const rho1Steps = p1.rho * RADIUS_STEPS_TOTAL;
      const rho2Steps = p2.rho * RADIUS_STEPS_TOTAL;
      
      // 计算移动距离
      const deltaTheta = Math.abs(theta2Steps - theta1Steps);
      const deltaRho = Math.abs(rho2Steps - rho1Steps);
      
      // 补偿运动计算
      const compensation = deltaTheta * COMPENSATION_FACTOR;
      const rhoTotalMove = deltaRho + compensation;
      
      // 时间计算(双轴同步,取最大值)
      const thetaTime = deltaTheta / DEFAULT_SPEED;
      const rhoTime = rhoTotalMove / DEFAULT_SPEED;
      const moveTime = Math.max(thetaTime, rhoTime);
      
      totalTime += moveTime;
    }
    
    console.log('纯移动时间:', totalTime);
    
    // 4. 添加系统开销
    const pointCount = points.length;
    const accelDecelOverhead = totalTime * 0.15; // 加减速开销 15%
    const systemOverhead = pointCount * 0.002; // 系统处理开销 2ms/点
    const networkOverhead = totalTime * 0.05; // 网络任务开销 5%
    
    const finalDuration = Math.ceil(
      totalTime + accelDecelOverhead + systemOverhead + networkOverhead
    );
    
    console.log('计算完成，最终时长:', finalDuration);
    
    return {
      code: 0,
      message: '计算成功',
      data: {
        duration: finalDuration,
        pointCount: pointCount,
        pureMovingTime: Math.ceil(totalTime),
        breakdown: {
          accelDecelOverhead: Math.ceil(accelDecelOverhead),
          systemOverhead: Math.ceil(systemOverhead),
          networkOverhead: Math.ceil(networkOverhead)
        }
      }
    };
    
  } catch (error) {
    console.error('计算时长失败:', error);
    return {
      code: -1,
      message: '计算失败: ' + error.message,
      error: error.toString()
    };
  }
};
